import { Application } from '../Application';
import { BackendSession } from '../session/BackendSession';
import { logger } from '../util/logger';
import { miscCfg, RpcMsg, RpcMsgId } from '../util/defines';
import { Server } from './Server';

/**
 * 后端服务器
 */
export class BackendServer extends Server {

    constructor(app: Application, onStart?: () => void) {
        super(app, onStart);
        logger.info(`${this.app.svr.id}已启动,Rpc服务监听${this.app.svr.port}端口`, this, "constructor");
        this.connectMaster();
    }

    /**
     * 发送消息到客户端
     * @param sid 
     * @param uid 
     * @param msgId 
     * @param msg 
     */
    send(sid: string, uid: number, msgId: number, msg?: any) {
        this.app.rpcService.send(sid, RpcMsgId.msgSend, { uid, data: miscCfg.msgCoder.encode(msgId, msg) });
    }

    /**
     * 发送多条消息到客户端
     * @param sid 
     * @param uid 
     * @param msgs 
     */
    sends(sid: string, uid: number, msgs: { msgId: number; msg?: any; }[]) {
        let datas: Uint8Array[] = [];
        for (let msg of msgs) {
            datas.push(miscCfg.msgCoder.encode(msg.msgId, msg.msg));
        }
        this.app.rpcService.send(sid, RpcMsgId.msgSend, { uid, datas });
    }

    /**
     * 广播消息到客户端
     * @param sidUids
     * @param msgId 
     * @param msg 
     */
    boardcast(sidUids: { [sid: string]: number[] }, msgId: number, msg?: any) {
        let data = miscCfg.msgCoder.encode(msgId, msg);
        for (let sid in sidUids) {
            let uids = sidUids[sid];
            this.app.rpcService.send(sid, RpcMsgId.msgSend, { uids, data });
        }
    }

    /**
     * 广播多条消息到客户端
     * @param sidUids
     * @param msgs 
     */
    boardcasts(sidUids: { [sid: string]: number[] }, msgs: { msgId: number; msg?: any; }[]) {
        let datas: Uint8Array[] = [];
        for (let msg of msgs) {
            datas.push(miscCfg.msgCoder.encode(msg.msgId, msg.msg));
        }
        for (let sid in sidUids) {
            let uids = sidUids[sid];
            this.app.rpcService.send(sid, RpcMsgId.msgSend, { uids, datas });
        }
    }

    /**
     * 处理msg消息
     * @param rpcMsg 
     */
    handleMsg(rpcMsg: RpcMsg<RpcMsgId.msgHandler>) {
        try {
            let msg = miscCfg.msgCoder.decode(rpcMsg.data as Buffer);
            let sess = new BackendSession(this.app, rpcMsg.sessBuf);
            let [_, msgHandler, msgHandlerFunc] = this.app.msgCfg[msg.msgId];
            this.msgHandlers[msgHandler][msgHandlerFunc](sess, msg.msg, msg.msgId);
        } catch (err: any) {
            logger.error("处理Msg时出现错误" + err.stack, this, this.handleMsg);
        }
    }

}